package com.demodis.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.demodis.dao.ModelDaoI;
import com.demodis.dao.PermissionDaoI;
import com.demodis.dao.impl.ModelDaoImpl;
import com.demodis.dao.impl.PermissionDaoImpl;
import com.demodis.domain.TblModel;
import com.demodis.domain.TblPermission;
import com.demodis.service.PermissionServiceI;
import com.demodis.util.Utils;

public class PermissionServiceImpl implements PermissionServiceI {

	PermissionDaoI permDao = new PermissionDaoImpl();
	ModelDaoI modelDao = new ModelDaoImpl();
	
	@Override
	public Object getPermissions() {
		List<TblModel> listModel = modelDao.getModel(true);
		List<TblPermission> listPerm = permDao.getPermissions();
		
		List<Object> rows = new ArrayList<Object>();
		Map<String, Object> row;
		
		for(TblModel model : listModel) {
			row = new HashMap<String, Object>();
			row.put("id", model.getModId());
			row.put("text", model.getModName());
			row.put("pid", model.getParMod());
			row.put("url", model.getModUrl());
			rows.add(row);
		}
		for(TblPermission perm : listPerm) {
			row = new HashMap<String, Object>();
			row.put("id", perm.getPermId());
			row.put("text", perm.getPermName());
			row.put("pid", perm.getModId());
			row.put("url", perm.getPermUrl());
			row.put("permValue", perm.getPermValue());
			rows.add(row);
		}
		
		return rows;
	}

	@Override
	public boolean save(TblPermission perm) {
		perm.setPermId(UUID.randomUUID().toString());
		return permDao.save(perm);
	}

	@Override
	public boolean modify(TblPermission perm) {
		return permDao.modify(perm);
	}

	@Override
	public boolean delete(TblPermission perm) {
		return permDao.delete(perm);
	}

	@Override
	public boolean distribute(TblPermission perm) {
		return permDao.distribute(perm);
	}

	@Override
	public boolean existPerm(Integer userId, String permUrl) {
		int permTotalValue = permDao.getUserPermValue(userId);
		int permValue = permDao.getPermValue(permUrl);
		if(permValue == 0) {
			return true;
		}
		return Utils.existPerm(permTotalValue, permValue);
	}

}
